package cn.yunhe.dao.impl;

import cn.yunhe.dao.INewsDao;
import cn.yunhe.entity.News;
import cn.yunhe.entity.Page;
import org.hibernate.Query;
import org.hibernate.Session;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

@Repository("newsDao")
@Transactional
public class NewsDaoImpl extends HibernateDaoSupport implements INewsDao {

    @Override
    public News getNews(int id) {
        return getHibernateTemplate().get(News.class, id);
    }

    @Override
    public List<News> getAllNews() {
        return getHibernateTemplate().find("from News");
    }

    @Override
    public Page getNewsByPage(int pageNum, int pageSize) {
        Page page = new Page();
        List<News> newsList = new ArrayList<News>();

        StringBuilder hql = new StringBuilder("from News where 1=1");
        StringBuilder countHql = new StringBuilder("select count(id) from News where 1=1");

        //开始的索引
        int fromIndex = pageSize * (pageNum - 1);

        Session session = null;
        //获取被spring托管的session
        session = this.getHibernateTemplate().getSessionFactory().getCurrentSession();

        Query query = session.createQuery(hql.toString());
        Query countQuery = session.createQuery(countHql.toString());

        //从第几条开始
        query.setFirstResult(fromIndex);
        //查询几条
        query.setMaxResults(pageSize);
        //获取查询结果
        newsList = query.list();

        List countResult = countQuery.list();
        Long totalRecord = ((Long) countResult.get(0)).longValue();        //总记录数

        //总页数
        Long totalPage = totalRecord % pageSize == 0 ? totalRecord / pageSize : (totalRecord / pageSize) + 1;
        //构造page对象，封装数据
        page.setPageSize(pageSize);
        page.setCurrentPage(pageNum);
        page.setDataList(newsList);
        page.setTotalPage(totalPage);
        page.setTotalRecord(totalRecord);

        return page;

    }
}
